package com.dfdchem.imd.kaiwu.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.adapter.SysMessageDetailAdapter;
import com.dfdchem.imd.kaiwu.adapter.UserMessageDetailAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.model.MessageType;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.RespList;
import com.dfdchem.imd.kaiwu.model.SysMessage;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.KeyboardChangeListener;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


@Route(path = RouterPath.MESSAGE_DETAIL_ACTIVITY)
public class MessageDetailActivity extends BaseActivity implements View.OnClickListener, OnHttpResponseListener, OnRefreshListener, View.OnFocusChangeListener, TextWatcher {
    private static final String TAG = "MessageDetailActivity";

    @Autowired
    public User fromUser;

    @Autowired
    public User toUser;

    @Autowired
    public int MESSAGE_TYPE;

    public static int MESSAGE_TYPE_SYS = 1;
    public static int MESSAGE_TYPE_USER = 2;

    private TextView title;

    private SmartRefreshLayout refreshLayout;

    private RecyclerView message_recyclerView;

    private LinearLayout input_layout;
    private EditText edit_text;
    private ImageView input_plus;
    private Button input_send;

    private SysMessageDetailAdapter sysMessageDetailAdapter;
    private UserMessageDetailAdapter userMessageDetailAdapter;

    private Timer mTimer;

    private final static int request_code_get_message = 1;
    private final static int request_code_send_message = 2;
    private final static int request_code_set_message_read = 3;

    private boolean isScrolled = false;

    private SysMessage lastMessage;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, MessageDetailActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_sys_detail);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        Log.d(TAG, this.getClass().getSimpleName() + " initView");

        title = findViewById(R.id.title);

        refreshLayout = findView(R.id.refreshLayout);

        // 系统消息
        message_recyclerView = findView(R.id.message_recyclerView);

        input_layout = findView(R.id.input_layout);
        if (MESSAGE_TYPE == MESSAGE_TYPE_SYS) {
            input_layout.setVisibility(View.GONE);
        }
        edit_text = findView(R.id.edit_text);
        input_plus = findView(R.id.input_plus);
        input_send = findView(R.id.input_send);

        message_recyclerView.setHasFixedSize(true);
        message_recyclerView.setLayoutManager(new LinearLayoutManager(this));
        if (MESSAGE_TYPE == MESSAGE_TYPE_USER) {
            userMessageDetailAdapter = new UserMessageDetailAdapter(this, fromUser, toUser);
            message_recyclerView.setAdapter(userMessageDetailAdapter);
        } else {
            sysMessageDetailAdapter = new SysMessageDetailAdapter(this, fromUser, toUser);
            message_recyclerView.setAdapter(sysMessageDetailAdapter);
        }
    }

    @Override
    protected void onResume() {
        Log.d(TAG, this.getClass().getSimpleName() + " onResume");
        super.onResume();

        if (mTimer == null) {
            mTimer = new Timer();
            TimerTask mTimerTask = new TimerTask() {//创建一个线程来执行run方法中的代码
                @Override
                public void run() {
                    getMessage();
                }
            };
            mTimer.scheduleAtFixedRate(mTimerTask, 0, 1000);
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onDestroy");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        super.onPause();
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void initData() {
        Log.d(TAG, this.getClass().getSimpleName() + " initData");
        title.setText(fromUser.getUserName() == null ? "已注销":fromUser.getUserName());
        showProgressDialog("正在加载...");
    }

    private void getMessage(){
        Log.d(TAG, "getMessageDetail");
        if (fromUser == null || fromUser.getId() <= 0) {
            return;
        }
        runThread(TAG + "getMessageDetail", new Runnable() {
            @Override
            public void run() {
                if (MESSAGE_TYPE == MESSAGE_TYPE_USER) {
                    RequestUtil.get_user_message_list(fromUser.getId(), request_code_get_message, MessageDetailActivity.this);
                } else {
                    RequestUtil.get_sys_message_list(fromUser.getId(), request_code_get_message, MessageDetailActivity.this);
                }
            }
        });
    }

    @Override
    public void initEvent() {
        Log.d(TAG, this.getClass().getSimpleName() + " initEvent");
        refreshLayout.setOnRefreshListener(this);
        edit_text.setOnFocusChangeListener(this);
        edit_text.addTextChangedListener(this);
        input_send.setOnClickListener(this);

        new KeyboardChangeListener(this).setKeyboardListener(new KeyboardChangeListener.KeyboardListener() {
            @Override
            public void onKeyboardChange(boolean isShow, int keyboardHeight) {
                Log.d(TAG, "isShow = [" + isShow + "], keyboardHeight = [" + keyboardHeight + "]");
                if (sysMessageDetailAdapter != null) {
                    message_recyclerView.scrollToPosition(sysMessageDetailAdapter.getItemCount()-1);
                }

                if (userMessageDetailAdapter != null) {
                    message_recyclerView.scrollToPosition(userMessageDetailAdapter.getItemCount()-1);
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.input_send:
                String content = edit_text.getEditableText().toString().trim();
                if (content.equals("")) return;
                lastMessage = new SysMessage();
                lastMessage.setTo(fromUser.getId());
                lastMessage.setFrom(toUser.getId());
                lastMessage.setContent(content);
                lastMessage.setContentType(MessageType.TEXT.getType());
                lastMessage.setSendTime(new Date());

                runThread(TAG + "sendMessage", new Runnable() {
                    @Override
                    public void run() {
                        RequestUtil.send_message(lastMessage, request_code_send_message, MessageDetailActivity.this);
                    }
                });

                if (userMessageDetailAdapter != null) {
                    if (userMessageDetailAdapter.getMessages() != null) {
                        userMessageDetailAdapter.getMessages().add(lastMessage);
                    } else {
                        List<SysMessage> list = new ArrayList<>();
                        list.add(lastMessage);
                        userMessageDetailAdapter.setMessages(list);
                    }

                    userMessageDetailAdapter.notifyDataSetChanged();
                }

                edit_text.setText("");
                if (userMessageDetailAdapter != null) {
                    message_recyclerView.smoothScrollToPosition(userMessageDetailAdapter.getItemCount()-1);
                }
                break;
        }
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        Log.d(TAG, "onHttpResponse requestCode:" + requestCode + " resultJson:" + resultJson);
        if (requestCode == request_code_get_message) {
            dismissProgressDialog();
        }
        if (e != null) {
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_message:
                RespList<SysMessage> resp = JSON.parseRespList(resultJson, SysMessage.class);
                if (resp == null || resp.getCode() != 200 || resp.getData() == null) {
                    Toast.makeText(this, resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    if (refreshLayout.getState() == RefreshState.Refreshing || refreshLayout.getState() == RefreshState.None) {
                        refreshLayout.finishRefresh(250);
                    }
                    return;
                }

                List<SysMessage> messages = resp.getData();
                if (messages != null && messages.size() > 0) {
                    // 翻转数组
                    Collections.reverse(messages);
                    if (MESSAGE_TYPE == MESSAGE_TYPE_USER) {
                        userMessageDetailAdapter.setMessages(messages);
                        userMessageDetailAdapter.notifyDataSetChanged();
                        if (!isScrolled)
                        {
                            isScrolled = true;
                            message_recyclerView.smoothScrollToPosition(userMessageDetailAdapter.getItemCount()-1);
                        }
                    } else {
                        sysMessageDetailAdapter.setMessages(messages);
                        sysMessageDetailAdapter.notifyDataSetChanged();
                        if (!isScrolled) {
                            isScrolled = true;
                            message_recyclerView.smoothScrollToPosition(sysMessageDetailAdapter.getItemCount()-1);
                        }
                    }
                    setMessageRead(messages.get(messages.size() - 1).getId());
                }

                refreshLayout.finishRefresh(250);
                break;
            case request_code_send_message:
                Resp<String> resp1 = JSON.parseResp(resultJson, String.class);
                if (resp1 == null || resp1.getCode() != 200) {
                    Toast.makeText(this, resp1 != null ? resp1.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
            case request_code_set_message_read:
                Resp<String> resp2 = JSON.parseResp(resultJson, String.class);
                Log.d(TAG, "resp2:" + resultJson);
                if (resp2 == null || resp2.getCode() != 200) {
                    latest_id = 0;
                    Toast.makeText(this, resp2 != null ? resp2.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
        }
    }

    private long latest_id;
    // 设置消息已读
    private void setMessageRead(long id) {
        if (latest_id != 0 && latest_id == id) return;
        if (latest_id != id) {
            latest_id = id;
        }

        // 系统消息需要记录每个人已读未读的状况
        User toUser = DataManager.getInstance().getUser();
        if (toUser == null || toUser.getId() <= 0) return;

        runThread(TAG + "setMessageRead", new Runnable() {
            @Override
            public void run() {
                RequestUtil.set_message_read(MESSAGE_TYPE ,fromUser.getId(), id, request_code_set_message_read, MessageDetailActivity.this);
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getMessage();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        Log.d(TAG, "onFocusChange");
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            input_send.setVisibility(View.VISIBLE);
            input_plus.setVisibility(View.GONE);
        } else {
            input_send.setVisibility(View.GONE);
            input_plus.setVisibility(View.VISIBLE);
        }
    }

    private int editTextLastHeight = 0;
    @Override
    public void afterTextChanged(Editable s) {
        if (editTextLastHeight != edit_text.getHeight()) {
            if (userMessageDetailAdapter != null) {
                message_recyclerView.scrollToPosition(userMessageDetailAdapter.getItemCount()-1);
            }
            editTextLastHeight = edit_text.getHeight();
        }
    }
}